package com.pandas.community.controller.interceptor;

import com.pandas.community.Utils.CookieUtil;
import com.pandas.community.Utils.HostHolder;
import com.pandas.community.entity.LoginTicket;
import com.pandas.community.entity.User;
import com.pandas.community.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Component
public class LoginTicketInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;

    // Controller之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ticket = CookieUtil.getValue(request,"ticket");

        if(ticket != null){
            LoginTicket loginTicket = userService.getLoginTicket(ticket);
            // 不为空， 且状态为有效， 且过期时间未到
            if(loginTicket != null && loginTicket.getStatus() != 1 && loginTicket.getExpired().after(new Date())){
                //根据login_ticket ——> userid ——> user
                User user = userService.selectById(loginTicket.getUserid());
                hostHolder.setUser(user);
            }
        }
        return  true;
    }

    //在Controller之后执行, 在模板引擎TemplateEngine之前，找到这个用户
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = hostHolder.getUser();
        if(user != null && modelAndView != null){
            modelAndView.addObject("loginUser", user);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        hostHolder.clear();
    }
}
